<script lang="ts" setup>
import type { DataFormOptionsProps } from '#/components/data-form';

import { ref } from 'vue';

import { getDeptTree, getRoleOptions } from '#/api';
import { DataForm } from '#/components/data-form';

import { useForm } from './data';

defineProps<{
    enums: Record<string, any>;
}>();

const dataFormRef = ref<InstanceType<typeof DataForm>>();
const roleData = ref<any[]>([]);
const deptData = ref<any[]>([]);

const { fields, rules } = useForm();

const open = (options: DataFormOptionsProps) => {
    Promise.all([getRoleOptions(), getDeptTree()]).then((rs) => {
        roleData.value = rs[0].data ?? [];
        deptData.value = rs[1].data ?? [];
        dataFormRef.value?.open(options);
    });
};

defineExpose({ open });
</script>
<template>
    <DataForm ref="dataFormRef" :fields="fields" :enums="enums" api="/system/user" title="用户信息" :rules="rules">
        <template #username="{ form }">
            <el-input v-model="form.username" placeholder="用户名" :disabled="!!form.id" />
        </template>
        <template #deptId="{ form }">
            <el-tree-select v-model="form.deptId" node-key="id" accordion clearable expand-on-click-node filterable :data="deptData" :props="{ label: 'name' }" />
        </template>
        <template #roles="{ form }">
            <el-select v-model="form.roles" value-key="id" :multiple="true" :max-collapse-tags="3">
                <el-option v-for="item in roleData" :key="item.id" :label="item.name" :value="item">
                    <span style="float: left">{{ item.name }}</span>
                    <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px; margin-left: 45px; padding-right: 5px">{{ item.code }}</span>
                </el-option>
            </el-select>
        </template>
    </DataForm>
</template>
